import os
import sys
from bib_file_parser import bib_file_extract,bib_item_extract

# def bib_file_extract(bib_file_path):
#     with open(bib_file_path, 'r', encoding='utf-8') as f:
#         bib_content = f.read()
#         bib_content = bib_content.split("\n@")
#         bib_content = [i for i in bib_content if i != ""]
#         bib_content = ["@" + i for i in bib_content]
#         bib_content = [i.replace("@@","@") for i in bib_content]
#         # bib_content = bib_content.replace("@@","@")
#     return bib_content

# def bib_item_extract(bib_item_list,item_key):
#     item_content = [bib_line for bib_line in bib_item_list if item_key in bib_line.split("=")[0]]
#     if len(item_content)!=0:
#         item_content = item_content[0]  
#     return item_content


def bib_repeat_check(bib_file_path):
    # 如果标题一样，则认为是重复的
    bib_content = bib_file_extract(bib_file_path)
    if sys.platform.startwith('darwin'):
        bib_file_name = bib_file_path.split("/")[-1].split(".")[0]
    if sys.platform.startwith('win'):
        bib_file_name = bib_file_path.split("\\")[-1].split(".")[0]
    file_dir_folder = os.path.dirname(bib_file_path)
    bib_title_list = []
    bib_content_new = []
    bib_file_name_new = bib_file_name + "_no_repeat_check.bib"
    bib_file_path_new = os.path.join(file_dir_folder, bib_file_name_new)
    for bib_item in bib_content:
        bib_item_list = bib_item.split("\n")
        title_line = bib_item_extract(bib_item_list,'Title')
        title_content = title_line.split("{")[1].split("}")[0]
        if title_content in bib_title_list:
            continue
        bib_title_list.append(title_content)
        bib_content_new.append(bib_item)    
    write_bib_file(bib_file_path_new,bib_content_new)
    return bib_file_name_new

def bib_item_label_gen(bib_item):
    # author_line = [bib_line for bib_line in bib_item if "uthor" in bib_line][0]
    author_line = bib_item_extract(bib_item,'uthor')
    author_1 = author_line.split("{")[1].split("and")[0]
    # year_line = [bib_line for bib_line in bib_item if "ear" in bib_line][0]
    year_line = bib_item_extract(bib_item,'ear')
    if len(year_line)!=0:
        year = year_line.split("{")[1].split("}")[0]
        label_pre = author_1.replace(" ", "_") + year
    else:
        label_pre = author_1.replace(" ", "_")
    return label_pre

# 如果标签已经存在，那么在标签后面加_2
def label_change(label_pre,label_list):
    label = label_pre
    while label in label_list:
        label = label + "_2"
    return label

# 将新创建的标签插入到bib_item的第一行
def label_insert(label,label_line):
    label_line = label_line.split("{")[0] + "{" + label + ","
    return label_line


def bib_label_check(bib_file_path):
    bib_content = bib_file_extract(bib_file_path)
    bib_file_name = bib_file_path.split("/")[-1].split(".")[0]
    # bib_file_name = bib_file_path.split("\\")[-1].split(".")[0]
    file_dir_folder = os.path.dirname(bib_file_path)
    bib_label_list = []
    bib_content_new = []
    for bib_item in bib_content:
        bib_item_list = bib_item.split("\n")

        bib_item_list = [i for i in bib_item_list if i != ""]
        # bib_label_item = bib_item_list[0]
        bib_label_item = bib_item_list[0].split("{")[1].split(",")[0]
        if bib_label_item=='':
            # author_line = [bib_line for bib_line in bib_item: if "uthor" in bib_line]
            label_pre = bib_item_label_gen(bib_item_list)
            label = label_change(label_pre,bib_label_list)
            label_line = label_insert(label,bib_item_list[0])
            bib_label_list.append(label)
            bib_item_list.insert(0,label_line)
            bib_item_list.remove(bib_item_list[1])
        else:
            if bib_label_item in bib_label_list:
                bib_label_item = label_change(bib_label_item,bib_label_list)
                label_line = label_insert(bib_label_item,bib_item_list[0])
                bib_item_list.insert(0,label_line)
                bib_item_list.remove(bib_item_list[1])
            bib_label_list.append(bib_label_item)
        bib_item = "\n".join(bib_item_list)
        bib_content_new.append(bib_item)
    bib_file_name_new = bib_file_name + "_label_check.bib"
    bib_file_path_new = os.path.join(file_dir_folder, bib_file_name_new)
    # bib_file_path_new = os.path.join(os.path.dirname(os.path.abspath(__file__)), bib_file_name_new)
    write_bib_file(bib_file_path_new,bib_content_new)
    return bib_file_name_new

def write_bib_file(bib_file_path,bib_content):
    with open(bib_file_path, 'w', encoding='utf-8') as f:
        f.write("\n".join(bib_content))

def bib_item_check(bib_file_path,must_items=[]):
    bib_content = bib_file_extract(bib_file_path)
    bib_file_name = bib_file_path.split("/")[-1].split(".")[0]
    # bib_file_name = bib_file_path.split("\\")[-1].split(".")[0]
    file_dir_folder = os.path.dirname(bib_file_path)
    # bib_title_list = []
    bib_content_new = []
    bib_file_name_new = bib_file_name + "_item_check.bib"
    bib_file_path_new = os.path.join(file_dir_folder, bib_file_name_new)
    # bib_file_path_new = os.path.join(os.path.dirname(os.path.abspath(__file__)), bib_file_name_new)
    if len(must_items)==0:
        # must_items = ['title','author']
        must_items = ['Title','Author']
    for bib_item in bib_content:
        item_abandon_flag = False
        bib_item_list = bib_item.split("\n")
        for must_item in must_items:
            must_item_line = bib_item_extract(bib_item_list,must_item)
            if len(must_item_line)==0:
                item_abandon_flag = True
        if not item_abandon_flag:
            bib_content_new.append(bib_item)    
    write_bib_file(bib_file_path_new,bib_content_new)
    return bib_file_name_new

if __name__ == "__main__": 
    bib_base_file =  os.path.join(os.path.dirname(os.path.abspath(__file__)),'1213')
    bib_file_path = os.path.join(bib_base_file, "behavior_tree_bib_mrm_all.bib")
    # bib_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "behavior_tree_bib_mrm_all.bib")
    bib_file_name_no_repeat = bib_repeat_check(bib_file_path)
    # bib_file_path_no_repeat =  os.path.join(os.path.dirname(os.path.abspath(__file__)), bib_file_name_no_repeat)
    bib_file_path_no_repeat =  os.path.join(bib_base_file, bib_file_name_no_repeat)
    bib_file_name_item_check = bib_item_check(bib_file_path_no_repeat)
    bib_file_path_item_check =  os.path.join(bib_base_file, bib_file_name_item_check)
    # bib_file_path_item_check =  os.path.join(os.path.dirname(os.path.abspath(__file__)), bib_file_name_item_check)
    bib_file_name_label_check = bib_label_check(bib_file_name_item_check)
